var app = {
    initialize: function() {
        this.bind();
    },
    bind: function() {
        document.addEventListener('deviceready', this.deviceready, false);
        $('.btn-upload').click(app.fileSelect);
    },
    deviceready: function() {
        // note that this is an event handler so the scope is that of the event
        // so we need to call app.report(), and not this.report()
        app.report('deviceready');
    },
    report: function(id) { 
        console.log("report:" + id);
        // hide the .pending <p> and show the .complete <p>
        document.querySelector('#' + id + ' .pending').className += ' hide';
        var completeElem = document.querySelector('#' + id + ' .complete');
        completeElem.className = completeElem.className.split('hide').join('');
    },
    fileSelect: function() {
        alert('test');
        navigator.camera.getPicture(app.uploadPhoto,
                                    function(message) { alert('get picture failed'); },
                                    { quality: 50,
                                    destinationType: navigator.camera.DestinationType.FILE_URI,
                                    sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }
                                    );
    },
    uploadPhoto: function(imageURI) {
        pop_uploading();
        var options = new FileUploadOptions();
        options.fileKey="file";
        options.fileName=imageURI.substr(imageURI.lastIndexOf('/')+1);
        options.mimeType="image/jpeg";
        
        var ft = new FileTransfer();
        ft.upload(imageURI, encodeURI("http://192.168.0.7:14041/file/upload/"), app.uploadSuccess, app.uploadFail, options);
    },
    uploadSuccess: function(r)
    {
        var data = JSON.parse(unescape(r.response));
        alert("Slug: " + data.slug);
        alert("Hash: " + data.hash);
        console.log("Sent = " + r.bytesSent);
        close_uploading(data.slug, data.hash);
    },
    uploadFail: function(error)
    {
        alert("An error has occurred: Code = " + error.code);
        console.log("upload error source " + error.source);
        console.log("upload error target " + error.target);
    }
};

function pop_uploading() {
    $('.uploading-box').fadeIn('fast');
    $('.uploading').center();
}

function close_uploading(slug, hash) {
    $('.uploading-box').fadeOut('fast', function() {
        window.location.href = 'download_file.html?slug=' + slug + '&hash=' + hash;
    });
}
